<template>
    <div class="page">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="220">
            <FormItem :label="$t('personal.100buyAccount')" prop="ottBuyAccount">
                {{ userInfo && userInfo.email }}
            </FormItem>
            <FormItem :label="$t('personal.FullName')" prop="realName">
                <RadioGroup v-model="formValidate.lang">
                    <Radio :label="$t('personal.Chinese')"></Radio>
                    <Radio :label="$t('personal.English')"></Radio>
                </RadioGroup>
                <FormItem label="">
                    <Row :gutter="8">
                        <Col span="8">
                        <Input v-model="formValidate.surname" :placeholder="$t('personal.LastName')"></Input>
                        </Col>
                        <Col span="8">
                        <Input v-model="formValidate.name" :placeholder="$t('personal.FirstName')"></Input>
                        </Col>
                    </Row>
                </FormItem>
            </FormItem>
            <FormItem :label="$t('personal.PhoneNumber')" prop="mobile">
                <Row :gutter="8">
                    <Col span="8">
                    <!--国际区号-->
                    <Select :label-in-value="true" v-model="formValidate.regionCode"
                        :placeholder="$t('user.pleaseSelect')">
                        <Option v-for="(item, index) in regionCodeList" :label="item.text" :value="item.code"
                            :key="item.code + index">
                            <div class="region-code">
                                <img class="region-code-icon" :src="item.flagImg" alt="">
                                <span>{{ item.text }}</span>
                            </div>
                        </Option>
                    </Select>
                    </Col>
                    <Col span="16">
                    <Input v-model="formValidate.mobile" placeholder=""></Input>
                    </Col>
                </Row>
            </FormItem>
            <FormItem :label="$t('personal.SocialAccount')" prop="platform">
                <RadioGroup v-model="formValidate.platform" type="button" button-style="solid">
                    <Radio :label="el.platform" v-for="el in socialList" :key="el.platformCode"></Radio>
                </RadioGroup>
                <div style="height: 10px" />
                <Input v-model="formValidate.account" placeholder=""></Input>
            </FormItem>
            <FormItem :label="$t('personal.Image')" prop="urlImageList">
                <div class="image-list">
                    <div class="image-item" v-for="(item, index) in urlImageList" :key="index">
                        <img :src="item" alt="">
                        <span @click="removeImage(index)" class="iconfont icon-shanchu"></span>
                    </div>
                </div>
                <Upload :show-upload-list="false" :headers="{
                    'X-Access-Token': userToken,
                    'lang': 'en_US'
                }" biz="chat" :data="{
                            biz: 'custom'
                        }" name="file" :disabled="uploadLoading" :max-size="3072" :before-upload="handleBeforeUpload"
                    :on-progress="onProgress" :on-success="onSuccess" :on-exceeded-size="handleMaxSize"
                    :action="uploadURL">
                    <div class="upload">
                        <t-loading v-if="uploadLoading"></t-loading>
                        <div v-else>
                            <img class="upload-image" src="@/assets/images/public/upload-icon.png" alt="">
                            <span class="text">{{ $t('customOrder.hint6') }}</span>
                        </div>
                    </div>
                </Upload>
            </FormItem>
            <FormItem :label="$t('personal.Name-organization')" prop="orgName">
                <Input v-model="formValidate.orgName" placeholder=""></Input>
            </FormItem>
            <FormItem :label="$t('personal.Nature-organization')" prop="orgType">
                <RadioGroup v-model="formValidate.orgType">
                    <Radio :label="$t('personal.Profit')"></Radio>
                    <Radio :label="$t('personal.NoProfit')"></Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="" prop="isRead">
                <Checkbox v-model="isRead">{{ $t('personal.agree') }}<span class="agreement-desc"
                        @click="toAggrement">{{ `《${$t('personal.PromotionAlliance')}》` }}</span></Checkbox>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="handleSubmit('formValidate')">{{ $t('personal.ApplyNow') }}</Button>
            </FormItem>
        </Form>
        <Modal v-model="visible" :title="$t('personal.TeamPromotion')" footer-hide width="300">
            <p style="text-align: center">{{ $t('personal.UnderReview') }}</p>
            <div style="text-align: right;margin-top:24px">
                <Button type="primary" style="background-color: #232323; border-color: #232323;"
                    @click="() => visible = false">{{ $t('personal.Confirm') }}</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { mapState } from "vuex";
import { teamPromoteOpen } from "@/api/invite";
import TLoading from "@/components/t-loading";
import { commonUpload } from "@/api/sys";

export default {
    name: "TeamPromotion",
    components: { TLoading },
    data() {
        return {
            uploadLoading: false,
            urlImageList: [], // 上传图片完整链接用来展示
            imageList: [], // 上传的图片列表
            uploadURL: commonUpload(),
            userToken: localStorage.getItem('USER_TOKEN'),
            visible: false,
            formValidate: {
                account: '',
                lang: '中文',
                regionCode: '',
                mobile: '',
                platform: '',
                realName: '',
                orgType: '盈利',
                orgName: '',
            },
            isRead: false,
            ruleValidate: {
                realName: [
                    {
                        required: true, message: 'The name cannot be empty', validator: (rule, value, callback) => {
                            const { surname, name } = this.formValidate
                            if (!surname || !name) {
                                callback(new Error('The name cannot be empty'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                platform: [
                    {
                        required: true, validator: (rule, value, callback) => {
                            if (!this.formValidate.platform) {
                                callback(new Error('The platform cannot be empty'));
                            } else if (!this.formValidate.account) {
                                callback(new Error('The account cannot be empty'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                urlImageList: [
                    {
                        required: true, message: 'The image cannot be empty', validator: (rule, value, callback) => {
                            if (!this.urlImageList.length) {
                                callback(new Error('The image cannot be empty'));
                            } else {
                                callback();
                            }
                        }, trigger: 'change'
                    }
                ]
            }
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.userInfo,
            userLanguage: state => state.personal.userLanguage,
            regionCodeList: (state) => {
                // 国际区号
                let list = [];
                if (state.config.config) {
                    list = state.config.config.regionCodeList;
                }
                return list;
            },
            socialList: (state) => {
                // 社交账号平台
                let list = [];
                if (state.config.config) {
                    list = state.config.config.socialList;
                }
                return list;
            },
            articleAgreementGroup: (state) => {
                // 100buy平台推广协议-t团体
                let obj = '';
                if (state.config.config) {
                    obj = state.config.config.articleMap.CFG_ARTICLE_GROUP_PROMOTION;
                }
                return obj;
            }
        })
    },
    methods: {
        toAggrement() {
            let toUrl = this.$router.resolve({
                path: '/notice/details',
                query: {
                    id: this.articleAgreementGroup && this.articleAgreementGroup.id
                }
            });
            window.open(toUrl.href, '_black')
        },
        removeImage(index) {
            // 删除图片
            this.imageList.splice(index, 1);
            this.urlImageList.splice(index, 1);
        },
        onProgress(event, file, fileList) {
            // console.log('上传的钩子',event, file, fileList)
        },
        handleMaxSize(file) {
            this.uploadLoading = false;
            this.$Message.error(`File ${file.name} is too large, no more than 3M.`);
        },
        onSuccess(response) {
            console.log('response: ', response);
            // 上传成功
            this.uploadLoading = false;
            if (response.code == 0 || response.code == 200 || response.code == 201) {
                let data = response.result;
                this.urlImageList.push(data.url);
                this.imageList.push(data.path);
            } else {
                this.$Message.error(response.message);
            }
        },
        onError(error, file) {
            this.$Message.error(this.$t('personal.uploadFailure'));
        },
        handleBeforeUpload(file) {
            this.uploadLoading = true;
        },
        handleSubmit(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if (!this.isRead) {
                        return this.$Message.error(this.$t('personal.PleaseAgreement'));
                    }
                    const { surname, name, orgType, ...rest } = this.formValidate
                    const params = {
                        ...rest,
                        realName: `${surname} ${name}`,
                        imageList: this.imageList,
                        orgType: orgType === this.$t('personal.Profit') ? 'PROFIT ' : 'NON_PROFIT '
                    }
                    teamPromoteOpen(params).then(({ code, message }) => {
                        if (code == 200) {
                            // this.visible = true;
                            this.$Message.success(message || 'Success!');
                            this.$router.push(`/user/invite`)
                        } else {
                            this.$Message.error(message || 'Fail!');
                        }
                    }).catch()
                } else {
                    this.$Message.error('Fail!');
                }
            })
        },
    }
}
</script>

<style scoped lang="less">
.page {
    padding: 25px 0;

    .agreement-desc {
        color: #E76202;
    }

    .upload-image {
        width: 100px;
        height: 100px;
        margin-right: 8px;
    }

    .image-list {
        display: flex;
        flex-wrap: wrap;

        .image-item {
            position: relative;
            margin-right: 6px;
            margin-bottom: 6px;
            width: 100px;
            height: 100px;
            border-radius: 4px;
            overflow: hidden;

            img {
                display: block;
                width: 100%;
                height: 100%;
            }

            .iconfont {
                position: absolute;
                cursor: pointer;
                right: 6px;
                bottom: 6px;
                color: @t-text-color;
            }
        }
    }
}

.region-code-icon {
    width: 35px;
}
</style>